import React, { createContext, useContext, useState, useEffect } from 'react';
import axios from 'axios';

const AuthContext = createContext();

export function AuthProvider({ children }) {
  const [user, setUser] = useState(null);
  const [token, setToken] = useState(localStorage.getItem('token'));
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [isAuthenticated, setIsAuthenticated] = useState(false);

  // 初始化时检查token
  useEffect(() => {
    const initAuth = async () => {
      const savedToken = localStorage.getItem('token');
      if (savedToken) {
        try {
          const response = await axios.get('/api/auth/verify', {
            headers: { Authorization: `Bearer ${savedToken}` }
          });
          setUser(response.data.user);
          setToken(savedToken);
          setIsAuthenticated(true);
        } catch (error) {
          console.error('Token验证失败:', error);
          logout();
        }
      }
      setLoading(false);
    };
    initAuth();
  }, []);

  const login = async (email, password) => {
    try {
      console.log('尝试登录:', { email }); // 不记录密码

      // 验证输入
      if (!email || !password) {
        throw new Error('请输入邮箱和密码');
      }

      // 发送登录请求 - 修改这里的路径
      const response = await axios.post('/api/auth/login', { 
        email: email.trim(),
        password 
      });

      console.log('登录响应:', response.data);

      // 验证响应数据
      if (!response.data.token || !response.data.user) {
        throw new Error('服务器响应格式错误');
      }

      const { token, user } = response.data;
      
      // 保存认证信息
      localStorage.setItem('token', token);
      localStorage.setItem('userData', JSON.stringify(user));
      
      // 更新状态
      setUser(user);
      setIsAuthenticated(true);
      setError(null);
      
      // 设置全局请求头
      axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
      
      return true;
    } catch (error) {
      console.error('登录失败:', error);
      
      let errorMessage = '登录失败';
      
      if (error.response) {
        // 服务器响应错误
        if (error.response.status === 401) {
          errorMessage = '邮箱或密码错误';
        } else if (error.response.status === 400) {
          errorMessage = error.response.data.message || '请求数据无效';
        } else {
          errorMessage = error.response.data.message || '服务器错误';
        }
      } else if (error.request) {
        // 请求发送失败
        errorMessage = '无法连接到服务器';
      } else {
        // 其他错误
        errorMessage = error.message;
      }

      setError(errorMessage);
      throw new Error(errorMessage);
    }
  };

  const logout = () => {
    setUser(null);
    setToken(null);
    localStorage.removeItem('token');
    localStorage.removeItem('userData');
    delete axios.defaults.headers.common['Authorization'];
    setIsAuthenticated(false);
  };

  const updateUserStats = async () => {
    if (!user) return;
    
    try {
      const response = await axios.get(`/api/users/${user.id}/stats`);
      setUser(prev => ({
        ...prev,
        ...response.data
      }));
    } catch (error) {
      console.error('更新用户统计失败:', error);
    }
  };

  return (
    <AuthContext.Provider value={{ 
      user, 
      token, 
      login, 
      logout,
      loading,
      error,
      updateUserStats,
      isAuthenticated
    }}>
      {children}
    </AuthContext.Provider>
  );
}

export function useAuth() {
  return useContext(AuthContext);
} 